package com.our.shop.system.base.service.impl;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.our.shop.system.base.model.SerialNumber;
import com.our.shop.system.base.service.SerialNumberService;
import com.our.shop.system.common.AdminSessionListener;
import com.our.shop.system.util.DateUtil;
import com.our.shop.system.util.NumberUtil;

@Service("serialNumberService")
public class SerialNumberServiceImpl extends BaseService implements SerialNumberService{
	
	private static final Logger logger = LoggerFactory.getLogger(AdminSessionListener.class);
	public String getSerialNumberByDate(String prefix, String appType) throws Exception {
		if (StringUtils.isBlank(prefix)) {
			logger.error("prefix is empty");
			throw new Exception("prefix is empty");
		}
		if (StringUtils.isBlank(appType)) {
			logger.error("appType is empty");
			throw new Exception("appType is empty");
		}
		logger.info("prefix:" + prefix + ";appType:" + appType);

		StringBuffer resultSerialNumber = new StringBuffer(prefix);

		Calendar calendar = Calendar.getInstance();

		Date nowDate = calendar.getTime();
		String nowDateStr = DateUtil.date2Str(nowDate, "yyyyMMdd");
		nowDate = DateUtil.str2Date(nowDateStr, "yyyyMMdd");
		int number = 0;

		SerialNumber objParam = new SerialNumber();
		objParam.setAppType(appType);
		SerialNumber serialNumber = (SerialNumber) this.select("",objParam);
		if (serialNumber == null) {
			logger.info("serialNumber is null");
			number = 1;

			serialNumber = new SerialNumber();
			serialNumber.setAppType(appType);
			serialNumber.setSerialDate(nowDate);
			serialNumber.setNumber(Integer.valueOf(number));

			this.insert("",serialNumber);
		} else {
			if (nowDate.after(serialNumber.getSerialDate())) {
				serialNumber.setSerialDate(nowDate);
				number = 1;
			} else {
				number = serialNumber.getNumber().intValue() + 1;
			}
			serialNumber.setNumber(Integer.valueOf(number));

			this.update("",serialNumber);
		}

		resultSerialNumber.append(nowDateStr);
		String numberStr = NumberUtil.formatNumber(number, 4);
		resultSerialNumber.append(numberStr);

		logger.info("resultSerialNumber:" + resultSerialNumber);
		return resultSerialNumber.toString();
	}
}